package com.xc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xc.common.Const;
import com.xc.common.ServerResponse;
import com.xc.dao.*;
import com.xc.pojo.*;
import com.xc.service.*;
import com.xc.utils.DateTimeUtil;
import com.xc.utils.KeyUtils;
import com.xc.utils.stock.BuyAndSellUtils;
import com.xc.utils.stock.GeneratePosition;
import com.xc.utils.stock.GetStayDays;
import com.xc.utils.stock.sina.SinaStockApi;
import com.xc.vo.agent.AgentIncomeVO;
import com.xc.vo.position.*;
import com.xc.vo.stock.StockListVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * @author mipha
 * @version 1.0
 * @date 2019/2/16 3:04 PM
 */
@Service("iUserPositionService")
@Slf4j
public class UserPositionServiceImpl implements IUserPositionService {

    @Autowired
    UserPositionMapper userPositionMapper;
    @Autowired
    IUserService iUserService;
    @Autowired
    ISiteSettingService iSiteSettingService;
    @Autowired
    IStockService iStockService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserCashDetailMapper userCashDetailMapper;
    @Autowired
    IAgentUserService iAgentUserService;
    @Autowired
    AgentUserMapper agentUserMapper;
    @Autowired
    SiteTaskLogMapper siteTaskLogMapper;


    @Override
    @Transactional
    public ServerResponse buy(Integer stockId, Integer buyNum, Integer buyType
            , Integer lever, HttpServletRequest request) throws Exception {

        User user = iUserService.getCurrentRefreshUser(request);
        if(StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard())){
            return ServerResponse.createByErrorMsg("下单失败，请先实名认证");
        }
        BigDecimal user_enable_amt = user.getEnableAmt();

        log.info("用户 {} 下单，股票id ={} ，数量 = {} , 方向 = {} , 杠杆 = {}"
                , user.getId() , stockId , buyNum , buyType ,lever);

        if(user.getIsLock() == Const.UserLockStatus.lock){
            return ServerResponse.createByErrorMsg("下单失败，账户已被锁定");
        }

        //  网站设置
        SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
        if(siteSetting == null){
            log.error("下单出错，网站设置表不存在");
            return ServerResponse.createByErrorMsg("下单失败，系统设置错误");
        }

        //  是否在交易时间内
        String am_begin = siteSetting.getTransAmBegin();
        String am_end = siteSetting.getTransAmEnd();
        String pm_begin = siteSetting.getTransPmBegin();
        String pm_end = siteSetting.getTransPmEnd();
        boolean am_flag = BuyAndSellUtils.isTransTime(am_begin,am_end);
        boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin,pm_end);
        log.info("是否在上午交易时间 = {} 是否在下午交易时间 = {}" , am_flag,pm_flag);
        if(am_flag == false && pm_flag == false){
            return ServerResponse.createByErrorMsg("下单失败，不在交易时段内");
        }

        //  股票是否存在
        Stock stock = null;
        ServerResponse stock_res = iStockService.findStockById(stockId);
        if(!stock_res.isSuccess()){
            return ServerResponse.createByErrorMsg("下单失败，股票代码错误");
        }
        stock = (Stock)stock_res.getData();
        //  判断当前股票能不能买卖
        if(stock.getIsLock() != Const.StockLock.no_lock){
            return ServerResponse.createByErrorMsg("下单失败，当前股票不能交易");
        }

        //  判断购买数量 前端传入的数量单位 股
        if(buyNum < siteSetting.getBuyMinNum() ){
            return ServerResponse.createByErrorMsg("下单失败，购买数量小于"
                    + siteSetting.getBuyMinNum() + "股");
        }
        if(buyNum >siteSetting.getBuyMaxNum()){
            return ServerResponse.createByErrorMsg("下单失败，购买数量大于"
                    + siteSetting.getBuyMaxNum() + "股");
        }

        /**
         *  获取股票现价
         */
        StockListVO stockListVO = SinaStockApi
                .assembleStockListVO(SinaStockApi.getSinaStock(stock.getStockGid()));

        BigDecimal now_price = new BigDecimal(stockListVO.getNowPrice());

        //  停牌不能买入
        if(now_price.compareTo(new BigDecimal("0")) == 0){
            return ServerResponse.createByErrorMsg("报价0，请稍后再试");
        }

        //  股票当前涨跌幅
        double stock_crease = stockListVO.getHcrate().doubleValue();

        //  判断是否涨停
        BigDecimal zsPrice = new BigDecimal(stockListVO.getPreclose_px());
        //  涨停价 = 6.97 * 0.1 + 6.97 涨停价需要四舍五入
        BigDecimal ztPrice = zsPrice.multiply(new BigDecimal("0.1")).add(zsPrice);
        ztPrice = ztPrice.setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal chaPrice = ztPrice.subtract(zsPrice);
        BigDecimal ztRate = chaPrice.multiply(new BigDecimal("100"))
                .divide(zsPrice,2, BigDecimal.ROUND_HALF_UP);

        log.info("股票当前涨跌幅 = {} 涨停幅度 = {}" , stock_crease,ztRate);
        if(new BigDecimal(String.valueOf(stock_crease)).compareTo(ztRate) == 0){
            return ServerResponse.createByErrorMsg("当前股票已涨停不能买入");
        }

        //  判断股票是不是大于最大涨跌幅
        int maxcrease = siteSetting.getCreaseMaxPercent().intValue();
        if(stock_crease > 0){
            if(stock_crease >= maxcrease){
                return ServerResponse.createByErrorMsg("下单失败，股票当前涨幅:"
                        +stock_crease + ",大于最大涨幅:" + maxcrease);
            }
        }
        if(stock_crease < 0){   //  如果跌了-8  跌幅为7个点
            if( -stock_crease > maxcrease){
                return ServerResponse.createByErrorMsg("下单失败，股票当前跌幅:"
                        +stock_crease + ",大于最大跌幅:" + maxcrease);
            }
        }


        //  杠杆后总资金
        BigDecimal buy_amt = now_price.multiply(new BigDecimal(buyNum));

        //  实际所需要资金
        BigDecimal buy_amt_autual = buy_amt.divide(new BigDecimal(lever)
                ,2,BigDecimal.ROUND_HALF_UP);

        //  判断最小购买金额
        int compareInt = buy_amt_autual.compareTo(new BigDecimal(siteSetting.getBuyMinAmt()));
        if(compareInt == -1){
            return ServerResponse.createByErrorMsg("下单失败，购买金额小于"
                    + siteSetting.getBuyMinAmt() + "元");
        }

        //  判断是否超过 购买单个股票最多价格（购买资金超过可用资金的百分比）buy_amt_autual 为配资前的金额
        BigDecimal max_buy_amt = user_enable_amt
                .multiply(siteSetting.getBuyMaxAmtPercent());
        int compareCwInt = buy_amt_autual.compareTo(max_buy_amt);
        if(compareCwInt == 1){
            return ServerResponse.createByErrorMsg("下单失败，不能超过可用资金的"
                    + siteSetting.getBuyMaxAmtPercent().multiply(new BigDecimal("100"))+"%");
        }

        //  判断用户可用金额是否足够    用户购买的金额是杠杆之后的
        int compareUserAmtInt = user_enable_amt.compareTo(buy_amt_autual);
        log.info("用户可用金额 = {}  实际购买金额 =  {}" , user_enable_amt , buy_amt_autual);
        log.info("比较 用户金额 和 实际 购买金额 =  {}" , compareUserAmtInt);
        if(compareUserAmtInt == -1){
            return ServerResponse.createByErrorMsg("下单失败，用户可用金额小于"
                    + buy_amt_autual + "元");
        }


        /**
         *  条件校验通过
         *  1.修改可用金额 - 占用资金
            2.请求券商接口生成持仓单
         */
        //        1.修改可用金额
        BigDecimal reckon_enable = user_enable_amt
                .subtract(buy_amt_autual);
        user.setEnableAmt(reckon_enable);
        int updateUserCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateUserCount > 0){
            log.info("【用户交易下单】修改用户金额成功");
        }else{
            log.error("用户交易下单】修改用户金额出错");
            throw new Exception("用户交易下单】修改用户金额出错");
        }

        //      2.保存持仓单
        UserPosition userPosition = new UserPosition();
        userPosition.setPositionType(user.getAccountType());
        userPosition.setPositionSn(KeyUtils.getUniqueKey());
        userPosition.setUserId(user.getId());
        userPosition.setNickName(user.getRealName());
        userPosition.setAgentId(user.getAgentId());
        userPosition.setStockCode(stock.getStockCode());
        userPosition.setStockName(stock.getStockName());
        userPosition.setStockGid(stock.getStockGid());
        userPosition.setStockSpell(stock.getStockSpell());
        userPosition.setBuyOrderId(GeneratePosition.getPositionId());
        userPosition.setBuyOrderTime(new Date());
        userPosition.setBuyOrderPrice(now_price);
        userPosition.setOrderDirection(buyType == 0 ? Const.StockPositionDirection.buy_rise
                : Const.StockPositionDirection.buy_fall);
        userPosition.setOrderNum(buyNum);

        //  设置锁仓状态
        userPosition.setIsLock(Const.UserPositionLockStatus.unlock);

        //  设置杠杆倍数
        userPosition.setOrderLever(lever);

        //  设置购买总资金
        userPosition.setOrderTotalPrice(buy_amt);

        //  设置手续费
        BigDecimal buy_fee_amt = buy_amt.multiply(siteSetting.getBuyFee())
                .setScale(2, BigDecimal.ROUND_HALF_UP);
        log.info("用户购买手续费（配资后总资金 * 百分比） = {}" , buy_fee_amt);
        userPosition.setOrderFee(buy_fee_amt);

        //  设置印花税
        BigDecimal buy_yhs_amt = buy_amt.multiply(siteSetting.getDutyFee())
                .setScale(2, BigDecimal.ROUND_HALF_UP);
        log.info("用户购买印花税（配资后总资金 * 百分比） = {}" , buy_yhs_amt);
        userPosition.setOrderSpread(buy_yhs_amt);

        //  设置盈亏浮动
        BigDecimal profit_and_lose = new BigDecimal("0");
        userPosition.setProfitAndLose(profit_and_lose);

        BigDecimal all_profit_and_lose = profit_and_lose
                .subtract(buy_fee_amt).subtract(buy_yhs_amt);
        userPosition.setAllProfitAndLose(all_profit_and_lose);

        //  设置留仓
        userPosition.setOrderStayDays(0);
        userPosition.setOrderStayFee(new BigDecimal("0"));

        int insertPositionCount = userPositionMapper.insert(userPosition);
        if(insertPositionCount > 0){
            log.info("【用户交易下单】保存持仓记录成功");
        }else{
            log.error("用户交易下单】保存持仓记录出错");
            throw new Exception("用户交易下单】保存持仓记录出错");
        }

        return ServerResponse.createBySuccess("下单成功");
    }

    @Override
    public ServerResponse sell(String positionSn, int doType) throws Exception {

        log.info("【用户交易平仓】 positionSn = {} ， dotype = {}" , positionSn ,doType);

        //  网站设置
        SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
        if(siteSetting == null){
            log.error("平仓出错，网站设置表不存在");
            return ServerResponse.createByErrorMsg("下单失败，系统设置错误");
        }

        //    判断是否在交易时间内)
        if(doType != Const.SellStockDoType.admin_do_type){
            String am_begin = siteSetting.getTransAmBegin();
            String am_end = siteSetting.getTransAmEnd();
            String pm_begin = siteSetting.getTransPmBegin();
            String pm_end = siteSetting.getTransPmEnd();
            boolean am_flag = BuyAndSellUtils.isTransTime(am_begin,am_end);
            boolean pm_flag = BuyAndSellUtils.isTransTime(pm_begin,pm_end);
            log.info("是否在上午交易时间 = {} 是否在下午交易时间 = {}" , am_flag,pm_flag);
            if(am_flag == false && pm_flag == false){
                return ServerResponse.createByErrorMsg("平仓失败，不在交易时段内");
            }
        }

        //  平仓记录
        UserPosition userPosition = userPositionMapper.findPositionBySn(positionSn);
        if(userPosition == null){
            return ServerResponse.createByErrorMsg("平仓失败，订单不存在");
        }

        //  用户
        User user = userMapper.selectByPrimaryKey(userPosition.getUserId());
        if(user.getIsLock() == Const.UserLockStatus.lock){
            return ServerResponse.createByErrorMsg("平仓失败，用户已被锁定");
        }

        if(userPosition.getSellOrderId() != null){
            return ServerResponse.createByErrorMsg("平仓失败，此订单已平仓");
        }

        //  是否锁仓
        if(Const.UserPositionLockStatus.lock == userPosition.getIsLock()){
            return ServerResponse.createByErrorMsg("平仓失败 "+userPosition.getLockMsg());
        }

        //  获取当前股票价格
        StockListVO stockListVO = SinaStockApi
                .assembleStockListVO(SinaStockApi.getSinaStock(userPosition.getStockGid()));

        BigDecimal now_price = new BigDecimal(stockListVO.getNowPrice());
        if(now_price.compareTo(new BigDecimal("0")) != 1){
            log.error("股票 = {} 收到报价 = {}" ,userPosition.getStockName() ,now_price);
            return ServerResponse.createByErrorMsg("报价0，平仓失败，请稍后再试");
        }


        //  当前的涨幅
        double stock_crease = stockListVO.getHcrate().doubleValue();

        //  判断是否跌停
        BigDecimal zsPrice = new BigDecimal(stockListVO.getPreclose_px());
        //  涨停价 = 6.97 * 0.1 + 6.97 涨停价需要四舍五入
        BigDecimal ztPrice = zsPrice.multiply(new BigDecimal("0.1")).add(zsPrice);
        ztPrice = ztPrice.setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal chaPrice = ztPrice.subtract(zsPrice);
        BigDecimal ztRate = chaPrice.multiply(new BigDecimal("100"))
                .divide(zsPrice,2, BigDecimal.ROUND_HALF_UP);
        ztRate = ztRate.negate();

        log.info("股票当前涨跌幅 = {} 跌停幅度 = {}" , stock_crease , ztRate);
        if(new BigDecimal(String.valueOf(stock_crease)).compareTo(ztRate) == 0){
            return ServerResponse.createByErrorMsg("当前股票已跌停不能卖出");
        }

        //  获取当前的涨幅
//        int maxcrease = siteSetting.getCreaseMaxPercent().intValue();
//        if(stock_crease > 0){
//            if(stock_crease >= maxcrease){
//                return ServerResponse.createByErrorMsg("卖出失败，股票当前涨幅:"
//                        +stock_crease + ",大于最大涨幅:" + maxcrease);
//            }
//        }
//        if(stock_crease < 0){   //  如果跌了-8  跌幅为7个点
//            if( -stock_crease > maxcrease){
//                return ServerResponse.createByErrorMsg("卖出失败，股票当前跌幅:"
//                        +stock_crease + ",大于最大跌幅:" + maxcrease);
//            }
//        }

        Integer buy_num = userPosition.getOrderNum();

        BigDecimal all_buy_amt = userPosition.getOrderTotalPrice();
        BigDecimal all_sell_amt = now_price.multiply(new BigDecimal(buy_num));

        BigDecimal profitLoss = new BigDecimal("0");
        if(Const.StockPositionDirection.buy_rise.equals(userPosition.getOrderDirection())){
            log.info("买卖方向：{}", "涨");
            //  如果是买涨，卖出 - 买入价格 ，否则反之
            profitLoss = all_sell_amt.subtract(all_buy_amt);
        }else{
            log.info("买卖方向：{}", "跌");
            profitLoss = all_buy_amt.subtract(all_sell_amt);
        }
        log.info("买入总金额 = {} , 卖出总金额 = {} , 盈亏 = {}" , all_buy_amt
                , all_sell_amt , profitLoss);

        /**
         *  平仓时收取的费用
         *  假如 10万 买了3万股票A 买了4万股票B
         *  总资金 10万 可用3万
         *  当平仓股票A时，手续费扣除五千，盈亏 -1000
         *  总资金变为 10万 - 6000 = 94000
         *
         *  那么可用资金应该是 可用资金3万 - 总盈亏 6000 + 占用保证金3万
         *  可用变为54000
         *
         *  1.  修改持仓单的手续费和印花税，并生成卖出持仓单
         *
         *  2.
         *      修改用户总资金
         *      总资金 + 总的盈亏浮动
         *      修改用户可用资金
         *      当前可用资金 + 总盈亏浮动 + 占用保证金()
         *
         *  3.  生成一条资金明细记录
         *
         */
        BigDecimal user_all_amt = user.getUserAmt();
        BigDecimal user_enable_amt = user.getEnableAmt();
        log.info("用户原本总资金 = {} , 可用 = {}",user_all_amt,user_enable_amt);

        BigDecimal buy_fee_amt = userPosition.getOrderFee();
        log.info("买入手续费 = {}",buy_fee_amt);

        BigDecimal orderSpread = userPosition.getOrderSpread();
        log.info("印花税 = {}",orderSpread);

        BigDecimal orderStayFee = userPosition.getOrderStayFee();
        log.info("留仓费 = {}",orderStayFee);

        BigDecimal sell_fee_amt = all_sell_amt.multiply(siteSetting.getSellFee())
                .setScale(2, BigDecimal.ROUND_HALF_UP);
        log.info("卖出手续费 = {}" , sell_fee_amt);

        BigDecimal all_fee_amt = buy_fee_amt.add(sell_fee_amt)
                .add(orderSpread).add(orderStayFee);
        log.info("总的手续费费用 = {}" , all_fee_amt);

        //  1.  修改持仓单
        userPosition.setSellOrderId(GeneratePosition.getPositionId());
        userPosition.setSellOrderPrice(now_price);
        userPosition.setSellOrderTime(new Date());

        //  (卖出也要收一次手续费，修改手续费)
        BigDecimal order_fee_all = buy_fee_amt.add(sell_fee_amt);
        userPosition.setOrderFee(order_fee_all);

        //  设置盈亏浮动
        userPosition.setProfitAndLose(profitLoss);
        //  设置总的盈亏浮动    profitLoss - 总的手续费
        BigDecimal all_profit = profitLoss.subtract(all_fee_amt);
        userPosition.setAllProfitAndLose(all_profit);

        int updatePositionCount = userPositionMapper.updateByPrimaryKeySelective(userPosition);
        if(updatePositionCount > 0){
            log.info("【用户平仓】修改浮动盈亏记录成功");
        }else{
            log.error("用户平仓】修改浮动盈亏记录出错");
            throw new Exception("用户平仓】修改浮动盈亏记录出错");
        }

        //  2.  修改用户的资金
        BigDecimal freez_amt = all_buy_amt
                .divide(new BigDecimal(userPosition.getOrderLever()),2,BigDecimal.ROUND_HALF_UP);

        BigDecimal reckon_all = user_all_amt.add(all_profit);
        BigDecimal reckon_enable = user_enable_amt.add(all_profit).add(freez_amt);

        log.info("用户平仓后的总资金  = {} , 可用资金 = {}" ,reckon_all,reckon_enable);
        user.setUserAmt(reckon_all);
        user.setEnableAmt(reckon_enable);
        int updateUserCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateUserCount > 0){
            log.info("【用户平仓】修改用户金额成功");
        }else{
            log.error("用户平仓】修改用户金额出错");
            throw new Exception("用户平仓】修改用户金额出错");
        }

        //  3.  保存资金明细记录
        UserCashDetail ucd = new UserCashDetail();
        ucd.setPositionId(userPosition.getId());
        ucd.setAgentId(user.getAgentId());
        ucd.setAgentName(user.getAgentName());
        ucd.setUserId(user.getId());
        ucd.setUserName(user.getRealName());
        ucd.setDeType(Const.UserCashDetailType.allprofit);
        ucd.setDeAmt(all_profit);
        ucd.setDeSummary("卖出股票，" + userPosition.getStockCode()+"/"+userPosition.getStockName()
                + ",占用本金：" + freez_amt + ",总手续费："+ all_fee_amt + ",盈亏："
                + profitLoss + "，总盈亏：" + all_profit);
//        ucd.setAddIp(ips);
//        ucd.setAddAddress(ipAddress);
        ucd.setAddTime(new Date());
        ucd.setIsRead(Const.UserCashDetailIsRead.no_read);

        int insertSxfCount = userCashDetailMapper.insert(ucd);
        if(insertSxfCount > 0){
            log.info("【用户平仓】保存明细记录成功");
        }else{
            log.error("用户平仓】保存明细记录出错");
            throw new Exception("用户平仓】保存明细记录出错");
        }

        return ServerResponse.createBySuccessMsg("平仓成功！");
    }

    @Override
    public ServerResponse lock(Integer positionId, Integer state, String lockMsg) {
        if(positionId == null || state == null){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        UserPosition position = userPositionMapper.selectByPrimaryKey(positionId);
        if(position == null){
            return ServerResponse.createByErrorMsg("持仓不存在");
        }

        if(position.getSellOrderId() != null){
            return ServerResponse.createByErrorMsg("平仓单不能锁仓");
        }

        if(state == Const.UserPositionLockStatus.lock){
            if(StringUtils.isBlank(lockMsg)){
                return ServerResponse.createByErrorMsg("锁仓提示信息必填");
            }
        }

        if(state == Const.UserPositionLockStatus.lock){
            position.setIsLock(Const.UserPositionLockStatus.lock);
            position.setLockMsg(lockMsg);
        }else{
            position.setIsLock(Const.UserPositionLockStatus.unlock);
        }

        int updateCount = userPositionMapper.updateByPrimaryKeySelective(position);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("操作成功");
        }else{
            return ServerResponse.createByErrorMsg("操作失败");
        }
    }

    @Override
    public ServerResponse del(Integer positionId) {
        if(positionId == null){
            return ServerResponse.createByErrorMsg("id不能为空");
        }
        UserPosition position = userPositionMapper.selectByPrimaryKey(positionId);
        if(position == null){
            return ServerResponse.createByErrorMsg("该持仓不存在");
        }
        if(position.getSellOrderId() == null){
            return ServerResponse.createByErrorMsg("持仓单不能删除！");
        }
        int updateCount = userPositionMapper.deleteByPrimaryKey(positionId);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("删除成功");
        }else{
            return ServerResponse.createByErrorMsg("删除失败");
        }
    }

    @Override
    public ServerResponse findMyPositionByCodeAndSpell(String stockCode, String stockSpell, Integer state, HttpServletRequest request,int pageNum,int pageSize) {
        User user = iUserService.getCurrentUser(request);

        PageHelper.startPage(pageNum,pageSize);

        //  查询持仓记录
        List<UserPosition> userPositions = userPositionMapper
                .findMyPositionByCodeAndSpell(user.getId(),stockCode,stockSpell,state);

        List<UserPositionVO> userPositionVOS = Lists.newArrayList();
        if(userPositions.size() > 0){
//            log.info("用户 {} 当前持仓订单 = {} " , user.getId() , userPositions.size());
            for (UserPosition position : userPositions){
                UserPositionVO userPositionVO = assembleUserPositionVO(position);
                userPositionVOS.add(userPositionVO);
            }
        }

        PageInfo pageInfo = new PageInfo(userPositions);
        pageInfo.setList(userPositionVOS);

        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public PositionVO findUserPositionAllProfitAndLose(Integer userId) {
        //  查询所有持仓中的股票
        List<UserPosition> userPositions = userPositionMapper
                .findPositionByUserIdAndSellIdIsNull(userId);

        BigDecimal allProfitAndLose = new BigDecimal("0");
        BigDecimal allFreezAmt = new BigDecimal("0");
        for (UserPosition position : userPositions){
            //  获取股票的现价
            StockListVO stockListVO = SinaStockApi.assembleStockListVO(SinaStockApi
                    .getSinaStock(position.getStockGid()));

            BigDecimal nowPrice = new BigDecimal(stockListVO.getNowPrice());

            /**
             *      集合竞价的时候 现价会返回 0
             *   如果当前价格不是为 0 ，则计算盈亏，否则盈亏返回0
             */
            if(nowPrice.compareTo(new BigDecimal("0")) != 0){

                BigDecimal buyPrice = position.getBuyOrderPrice();
                BigDecimal subPrice = nowPrice.subtract(buyPrice);

                BigDecimal profit_and_lose = subPrice.multiply(new BigDecimal(position.getOrderNum()));
                if(Const.StockPositionDirection.buy_fall.equals(position.getOrderDirection())){
                    //  如果是买跌，取反
                    profit_and_lose = profit_and_lose.negate();
                }

//                log.info("持仓股票 {} ,现价 = {} ,买入价格 = {} 差价 = {} 盈亏 = {}"
//                        ,position.getStockName(),nowPrice,buyPrice,subPrice,profit_and_lose);

                BigDecimal total_fee = position.getOrderFee()
                        .add(position.getOrderSpread()).add(position.getOrderStayFee());
//                log.info("总手续费 = {}" , total_fee);

                //  单个持仓单的总盈亏 = 盈亏 - 手续费
                BigDecimal position_profit = profit_and_lose.subtract(total_fee);
//                log.info("该持仓单的总盈亏 = {}" ,position_profit);

                allProfitAndLose = allProfitAndLose.add(position_profit);

                //  计算冻结保证金
                BigDecimal position_freez = position.getOrderTotalPrice()
                        .divide(new BigDecimal(position.getOrderLever()),2,BigDecimal.ROUND_HALF_UP);
                allFreezAmt = allFreezAmt.add(position_freez);
            }else{
                log.info("查询所有持仓单的总盈亏，现价返回0，当前为集合竞价");
            }

        }
        log.info("用户 = {} 所有持仓单的总盈亏 = {}" , userId , allProfitAndLose);
        log.info("用户 = {} 所有持仓单的冻结保证金 = {}" , userId , allFreezAmt);

        PositionVO positionVO = new PositionVO();
        positionVO.setAllProfitAndLose(allProfitAndLose);
        positionVO.setAllFreezAmt(allFreezAmt);
        return positionVO;
    }


    @Override
    public List<UserPosition> findPositionByUserIdAndSellIdIsNull(Integer userId) {
        //  查询所有持仓中的股票
        List<UserPosition> userPositions = userPositionMapper
                .findPositionByUserIdAndSellIdIsNull(userId);
        return userPositions;
    }

    @Override
    public ServerResponse listByAgent(Integer positionType, Integer state, Integer userId,
           Integer agentId, String positionSn, String beginTime ,String endTime,
           HttpServletRequest request, int pageNum, int pageSize) {
        //  当前登陆代理
        AgentUser currentAgent = iAgentUserService.getCurrentAgent(request);

        //  如果传入了agentId,首先判断agentId是否为当前代理下
        if(agentId != null){
            AgentUser agentUser = agentUserMapper.selectByPrimaryKey(agentId);
            if(agentUser.getParentId() != currentAgent.getId()){
                return ServerResponse.createByErrorMsg("不能查询非下级代理用户持仓");
            }
        }

        Integer searchId = null;
        if(agentId == null){
            searchId = currentAgent.getId();    //  如果传入id为空，查询登陆代理的用户
        }else{
            searchId = agentId;
        }

        //  转换日期格式
        Timestamp begin_time = null;
        if(StringUtils.isNotBlank(beginTime)){
            begin_time = DateTimeUtil.searchStrToTimestamp(beginTime);
        }
        Timestamp end_time = null;
        if(StringUtils.isNotBlank(endTime)){
            end_time = DateTimeUtil.searchStrToTimestamp(endTime);
        }

        PageHelper.startPage(pageNum,pageSize);

        List<UserPosition> userPositions = userPositionMapper
                .listByAgent(positionType ,state ,userId ,searchId ,positionSn ,begin_time ,end_time);

        List<AgentPositionVO> agentPositionVOS = Lists.newArrayList();
        for (UserPosition position : userPositions){
            AgentPositionVO agentPositionVO = assembleAgentPositionVO(position);
            agentPositionVOS.add(agentPositionVO);
        }

        PageInfo pageInfo = new PageInfo(userPositions);
        pageInfo.setList(agentPositionVOS);

        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse getIncome(Integer agentId, Integer positionType, String beginTime, String endTime) {
        if(StringUtils.isBlank(beginTime) || StringUtils.isBlank(endTime)){
            return ServerResponse.createByErrorMsg("时间不能为空");
        }
        //  转换日期格式
        Timestamp begin_time = null;
        if(StringUtils.isNotBlank(beginTime)){
            begin_time = DateTimeUtil.searchStrToTimestamp(beginTime);
        }
        Timestamp end_time = null;
        if(StringUtils.isNotBlank(endTime)){
            end_time = DateTimeUtil.searchStrToTimestamp(endTime);
        }

        List<UserPosition> userPositions = userPositionMapper
                .listByAgent(positionType , Const.PositionStatus.pcd , null , agentId , null ,begin_time ,end_time);
        log.info("查询到反佣周期内 订单数：{}" , userPositions.size());

        BigDecimal order_fee_amt = new BigDecimal("0");
        BigDecimal order_profit_and_lose = new BigDecimal("0");
        BigDecimal order_profit_and_lose_all = new BigDecimal("0");

        for(UserPosition position : userPositions){
            order_fee_amt = order_fee_amt.add(position.getOrderFee())
                    .add(position.getOrderSpread()).add(position.getOrderStayFee());
            order_profit_and_lose = order_profit_and_lose
                    .add(position.getProfitAndLose());
            order_profit_and_lose_all = order_profit_and_lose_all
                    .add(position.getAllProfitAndLose());
        }

        AgentIncomeVO agentIncomeVO = new AgentIncomeVO();
        agentIncomeVO.setOrderSize(userPositions.size());
        agentIncomeVO.setOrderFeeAmt(order_fee_amt);
        agentIncomeVO.setOrderProfitAndLose(order_profit_and_lose);
        agentIncomeVO.setOrderAllAmt(order_profit_and_lose_all);

        return ServerResponse.createBySuccess(agentIncomeVO);
    }

    @Override
    public ServerResponse listByAdmin(Integer agentId, Integer positionType, Integer state, Integer userId, String positionSn, String beginTime, String endTime, int pageNum, int pageSize) {

        PageHelper.startPage(pageNum,pageSize);

        //  转换日期格式
        Timestamp begin_time = null;
        if(StringUtils.isNotBlank(beginTime)){
            begin_time = DateTimeUtil.searchStrToTimestamp(beginTime);
        }
        Timestamp end_time = null;
        if(StringUtils.isNotBlank(endTime)){
            end_time = DateTimeUtil.searchStrToTimestamp(endTime);
        }

        List<UserPosition> userPositions = userPositionMapper
                .listByAgent(positionType ,state ,userId ,agentId ,positionSn ,begin_time ,end_time);

        List<AdminPositionVO> adminPositionVOS = Lists.newArrayList();
        for (UserPosition position : userPositions){
            AdminPositionVO adminPositionVO = assembleAdminPositionVO(position);
            adminPositionVOS.add(adminPositionVO);
        }

        PageInfo pageInfo = new PageInfo(userPositions);
        pageInfo.setList(adminPositionVOS);

        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public int CountPositionNum(Integer state, Integer accountType) {
        return userPositionMapper.CountPositionNum(state,accountType);
    }

    @Override
    public BigDecimal CountPositionProfitAndLose() {
        return userPositionMapper.CountPositionProfitAndLose();
    }

    @Override
    public BigDecimal CountPositionAllProfitAndLose() {
        return userPositionMapper.CountPositionAllProfitAndLose();
    }

    @Override
    public void doClosingStayTask() {
        //  扫描所有在持仓的订单
        List<UserPosition> userPositions = userPositionMapper.findAllStayPosition();

        //  查询设置表
//        SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
//        if(siteSetting == null){
//            log.error("网站设置表不存在");
//        }
//        log.info("当前系统设置最大留仓天数 = 【 {} 】",siteSetting.getStayMaxDays());

        if(userPositions.size() > 0){
            log.info("查询到正在持仓的订单数量 = {}" , userPositions.size());

            for (UserPosition position : userPositions){
                int stayDays = GetStayDays.getDays(GetStayDays.getBeginDate(position.getBuyOrderTime()));

                log.info("");
                log.info("开始处理 持仓订单id = {} 订单号 = {} 用户id = {} realName = {} 留仓天数 = {}"
                        ,position.getId(),position.getPositionSn(),position.getUserId()
                        ,position.getNickName(),stayDays);

                if(stayDays != 0 ){  // && stayDays <= siteSetting.getStayMaxDays()
                    log.info(" 开始收取 {} 天 留仓费",stayDays);
                    try {
                        closingStayTask(position,stayDays);
                    }catch (Exception e){
                        log.error("doClosingStayTask = ",e);
                    }
                }
//                else if(stayDays >  siteSetting.getStayMaxDays()){
//                    log.info("持仓订单 = {} , 留仓天数大于最大留仓天数，强制平仓并保存task" , position.getId());
//                    try {
//                        doSellStock(position.getPositionSn(), Const.SellStockDoType.admin_do_type);
//                    }catch (Exception e){
//                        log.error("(持仓天数大于设置的天数)强制平仓失败...",e);
//                    }
//                    //  保存task记录
//                    SiteTaskLog siteTaskLog = new SiteTaskLog();
//                    siteTaskLog.setTaskType(Const.SiteTaskType.forceStockSell_closingDay_TASK);
//                    siteTaskLog.setTaskCnt("定时任务强制平仓持仓单，订单号 = "+ position.getPositionSn()
//                            +",持仓天数大于" +siteSetting.getStayMaxDays()+ "持仓天数为"+stayDays);
//                    siteTaskLog.setTaskTarget("持仓天数大于 " +siteSetting.getStayMaxDays());
//                    siteTaskLog.setAddTime(new Date());
//                    siteTaskLog.setIsSuccess(0);
//                    siteTaskLog.setErrorMsg("");
//                    int insertTaskCount = siteTaskLogMapper.insert(siteTaskLog);
//                    if(insertTaskCount > 0){
//                        log.info("保存强制平仓(持仓天数大于设定天数)task任务成功");
//                    }else{
//                        log.error("保存强制平仓(持仓天数大于设定天数)task任务失败");
//                    }
//                }
                else{
                    log.info("持仓订单 = {} ,持仓天数0天,不需要处理...",position.getId());
                }

                log.info("修改留仓费 处理结束。");
                log.info("");
            }
            //  保存定时任务记录
            SiteTaskLog stl = new SiteTaskLog();
            stl.setTaskType(Const.SiteTaskType.closingStay);
            stl.setAddTime(new Date());
            stl.setIsSuccess(Const.SiteTaskStatus.success);
            stl.setTaskTarget("扣除留仓费，订单数量为" + userPositions.size());
            siteTaskLogMapper.insert(stl);
        }else{
            log.info("doClosingStayTask没有正在持仓的订单");
        }
    }
    @Override
    @Transactional
    public ServerResponse closingStayTask(UserPosition position,Integer stayDays) throws Exception{
        log.info("=================closingStayTask====================");
        log.info("修改留仓费，持仓id={},持仓天数={}",position.getId(),stayDays);
        //  如果持仓天数不为0，修改持仓记录表，并扣除用户的金额
        SiteSetting siteSetting = iSiteSettingService.getSiteSetting();
        if(siteSetting == null){
            log.error("修改留仓费出错，网站设置表不存在");
            return ServerResponse.createByErrorMsg("修改留仓费出错，网站设置表不存在");
        }

        //  单天持仓费
        BigDecimal stayFee = position.getOrderTotalPrice().multiply(siteSetting.getStayFee());

        BigDecimal allStayFee = stayFee.multiply(new BigDecimal(stayDays));

        log.info("总留仓费 = {}",allStayFee);

        //  修改持仓记录表
        position.setOrderStayFee(allStayFee);
        position.setOrderStayDays(stayDays);
        //  修改总的 盈亏 = 总盈亏 - allStayFee
        BigDecimal all_profit = position.getAllProfitAndLose().subtract(allStayFee);
        position.setAllProfitAndLose(all_profit);

        int updateCount = userPositionMapper.updateByPrimaryKeySelective(position);
        if(updateCount > 0){
            log.info("【closingStayTask收持仓费】修改持仓记录成功");
        }else{
            log.error("【closingStayTask收持仓费】修改持仓记录出错");
            throw new Exception("【closingStayTask收持仓费】修改持仓记录出错");
        }

        /**
         *  不扣除用户的资金，在平仓时一起结算
         */
        //  扣除用户的可用资金
//        User user = userMapper.selectByPrimaryKey(position.getUserId());
//        log.info("开始扣除用户的留仓费="+stayFee);
//        BigDecimal user_all_amt = user.getUserAmt();
//        BigDecimal user_enable_amt = user.getEnableAmt();
//        //  用户总金额 - 留仓费
//        BigDecimal reckon_all = user_all_amt.subtract(stayFee);
//        //  可用资金 - 留仓费
//        BigDecimal reckon_enable = user_enable_amt.subtract(stayFee);
//        log.info("用户{}原本总资金 = {} , 可用 = {}",user.getNickName(),user_all_amt,user_enable_amt);
//        log.info("用户{}扣除留仓费后的总资金 = {} , 可用 = {}",user.getNickName(),reckon_all,reckon_enable);
//        user.setUserAmt(reckon_all);
//        user.setEnableAmt(reckon_enable);
//        int updateUserCount = userMapper.updateByPrimaryKeySelective(user);
//        if(updateUserCount > 0){
//            log.info("【closingStayTask收持仓费】修改用户金额成功");
//        }else{
//            log.error("【closingStayTask收持仓费】修改用户金额出错");
//            throw new Exception("【closingStayTask收持仓费】修改用户金额出错");
//        }

        //  保存用户资金记录表
//        UserCashDetail lcf = new UserCashDetail();
//        lcf.setAgentId(user.getAgentId());
//        lcf.setAgentName(user.getAgentName());
//        lcf.setUserId(user.getId());
//        lcf.setUserName(user.getNickName());
//        lcf.setDeType(Const.UserCashDetailType.lcf);
//        lcf.setDeAmt(stayFee);
//        lcf.setDeSummary("系统扣除持仓订单【"+position.getId()+"】留仓费"
//                + stayFee.setScale(2,BigDecimal.ROUND_HALF_DOWN)
//                + "，扣除后总资金:"+reckon_all.setScale(2,BigDecimal.ROUND_HALF_DOWN));
//        lcf.setAddIp("");
//        lcf.setAddAddress("");
//        lcf.setAddTime(new Date());
//        lcf.setIsRead(Const.UserCashDetailIsRead.no_read);
//        int insertCount = userCashDetailMapper.insert(lcf);
//        if(insertCount > 0){
//            log.info("【closingStayTask收持仓费】保存资金记录表成功");
//        }else{
//            log.error("【closingStayTask收持仓费】保存资金记录表出错");
//            throw new Exception("【closingStayTask收持仓费】保存资金记录表出错");
//        }

        log.info("=======================================================");
        return ServerResponse.createBySuccess();
    }

    @Override
    public List<Integer> findDistinctUserIdList() {
        return userPositionMapper.findDistinctUserIdList();
    }


    private AdminPositionVO assembleAdminPositionVO(UserPosition position){
        AdminPositionVO adminPositionVO = new AdminPositionVO();

        adminPositionVO.setId(position.getId());
        adminPositionVO.setPositionSn(position.getPositionSn());
        adminPositionVO.setPositionType(position.getPositionType());
        adminPositionVO.setUserId(position.getUserId());
        adminPositionVO.setNickName(position.getNickName());
        adminPositionVO.setAgentId(position.getAgentId());
        adminPositionVO.setStockName(position.getStockName());
        adminPositionVO.setStockCode(position.getStockCode());
        adminPositionVO.setStockGid(position.getStockGid());
        adminPositionVO.setStockSpell(position.getStockSpell());
        adminPositionVO.setBuyOrderId(position.getBuyOrderId());
        adminPositionVO.setBuyOrderTime(position.getBuyOrderTime());
        adminPositionVO.setBuyOrderPrice(position.getBuyOrderPrice());
        adminPositionVO.setSellOrderId(position.getSellOrderId());
        adminPositionVO.setSellOrderTime(position.getSellOrderTime());
        adminPositionVO.setSellOrderPrice(position.getSellOrderPrice());
        adminPositionVO.setOrderDirection(position.getOrderDirection());
        adminPositionVO.setOrderNum(position.getOrderNum());
        adminPositionVO.setOrderLever(position.getOrderLever());
        adminPositionVO.setOrderTotalPrice(position.getOrderTotalPrice());
        adminPositionVO.setOrderFee(position.getOrderFee());
        adminPositionVO.setOrderSpread(position.getOrderSpread());
        adminPositionVO.setOrderStayFee(position.getOrderStayFee());
        adminPositionVO.setOrderStayDays(position.getOrderStayDays());

        adminPositionVO.setIsLock(position.getIsLock());
        adminPositionVO.setLockMsg(position.getLockMsg());


        PositionProfitVO positionProfitVO = getPositionProfitVO(position);
        adminPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
        adminPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
        adminPositionVO.setNow_price(positionProfitVO.getNowPrice());
//        log.info("assembleAgentPositionVO 设置 {} id = {} 方向 = {}  盈亏 = {}  总盈亏 = {}"
//                , position.getSellOrderId() == null ? "持仓单" : "平仓单"
//                , position.getId() ,position.getOrderDirection()
//                ,positionProfitVO.getProfitAndLose(),positionProfitVO.getAllProfitAndLose() );

        return adminPositionVO;
    }
    private AgentPositionVO assembleAgentPositionVO(UserPosition position){

        AgentPositionVO agentPositionVO = new AgentPositionVO();

        agentPositionVO.setId(position.getId());
        agentPositionVO.setPositionSn(position.getPositionSn());
        agentPositionVO.setPositionType(position.getPositionType());
        agentPositionVO.setUserId(position.getUserId());
        agentPositionVO.setNickName(position.getNickName());
        agentPositionVO.setAgentId(position.getAgentId());
        agentPositionVO.setStockName(position.getStockName());
        agentPositionVO.setStockCode(position.getStockCode());
        agentPositionVO.setStockGid(position.getStockGid());
        agentPositionVO.setStockSpell(position.getStockSpell());
        agentPositionVO.setBuyOrderId(position.getBuyOrderId());
        agentPositionVO.setBuyOrderTime(position.getBuyOrderTime());
        agentPositionVO.setBuyOrderPrice(position.getBuyOrderPrice());
        agentPositionVO.setSellOrderId(position.getSellOrderId());
        agentPositionVO.setSellOrderTime(position.getSellOrderTime());
        agentPositionVO.setSellOrderPrice(position.getSellOrderPrice());
        agentPositionVO.setOrderDirection(position.getOrderDirection());
        agentPositionVO.setOrderNum(position.getOrderNum());
        agentPositionVO.setOrderLever(position.getOrderLever());
        agentPositionVO.setOrderTotalPrice(position.getOrderTotalPrice());
        agentPositionVO.setOrderFee(position.getOrderFee());
        agentPositionVO.setOrderSpread(position.getOrderSpread());
        agentPositionVO.setOrderStayFee(position.getOrderStayFee());
        agentPositionVO.setOrderStayDays(position.getOrderStayDays());

        agentPositionVO.setIsLock(position.getIsLock());
        agentPositionVO.setLockMsg(position.getLockMsg());

        PositionProfitVO positionProfitVO = getPositionProfitVO(position);
        agentPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
        agentPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
        agentPositionVO.setNow_price(positionProfitVO.getNowPrice());

//        log.info("assembleAgentPositionVO 设置 {} id = {} 方向 = {}  盈亏 = {}  总盈亏 = {}"
//                , position.getSellOrderId() == null ? "持仓单" : "平仓单"
//                , position.getId() ,position.getOrderDirection()
//                ,positionProfitVO.getProfitAndLose(),positionProfitVO.getAllProfitAndLose() );

        return agentPositionVO;
    }

    private UserPositionVO assembleUserPositionVO(UserPosition position){
        UserPositionVO userPositionVO = new UserPositionVO();

        userPositionVO.setId(position.getId());
        userPositionVO.setPositionType(position.getPositionType());
        userPositionVO.setPositionSn(position.getPositionSn());
        userPositionVO.setUserId(position.getUserId());
        userPositionVO.setNickName(position.getNickName());
        userPositionVO.setAgentId(position.getAgentId());
        userPositionVO.setStockName(position.getStockName());
        userPositionVO.setStockCode(position.getStockCode());
        userPositionVO.setStockGid(position.getStockGid());
        userPositionVO.setStockSpell(position.getStockSpell());
        userPositionVO.setBuyOrderId(position.getBuyOrderId());
        userPositionVO.setBuyOrderTime(position.getBuyOrderTime());
        userPositionVO.setBuyOrderPrice(position.getBuyOrderPrice());
        userPositionVO.setSellOrderId(position.getSellOrderId());
        userPositionVO.setSellOrderTime(position.getSellOrderTime());
        userPositionVO.setSellOrderPrice(position.getSellOrderPrice());
        userPositionVO.setProfitTargetPrice(position.getProfitTargetPrice());
        userPositionVO.setStopTargetPrice(position.getStopTargetPrice());
        userPositionVO.setOrderDirection(position.getOrderDirection());
        userPositionVO.setOrderNum(position.getOrderNum());
        userPositionVO.setOrderLever(position.getOrderLever());
        userPositionVO.setOrderTotalPrice(position.getOrderTotalPrice());
        userPositionVO.setOrderFee(position.getOrderFee());
        userPositionVO.setOrderSpread(position.getOrderSpread());
        userPositionVO.setOrderStayFee(position.getOrderStayFee());
        userPositionVO.setOrderStayDays(position.getOrderStayDays());


        PositionProfitVO positionProfitVO = getPositionProfitVO(position);
        userPositionVO.setProfitAndLose(positionProfitVO.getProfitAndLose());
        userPositionVO.setAllProfitAndLose(positionProfitVO.getAllProfitAndLose());
        userPositionVO.setNow_price(positionProfitVO.getNowPrice());

//        log.info("assembleUserPositionVO设置 {} id = {} 方向 = {}  盈亏 = {}  总盈亏 = {}"
//                , position.getSellOrderId() == null ? "持仓单" : "平仓单"
//                , position.getId() ,position.getOrderDirection()
//                ,positionProfitVO.getProfitAndLose(),positionProfitVO.getAllProfitAndLose() );

        return userPositionVO;
    }

    private PositionProfitVO getPositionProfitVO(UserPosition position){
        /**
         *  这里要区分 持仓单和平仓单
         *  如果是持仓单 查询现价和盈亏
         *  如果是平仓单 查询平仓价
         */
        BigDecimal profitAndLose = new BigDecimal("0");
        BigDecimal allProfitAndLose = new BigDecimal("0");
        String nowPrice = "";

        if(position.getSellOrderId() != null){
            //  设置单子的浮动盈亏 = （卖出价 - 买入价）* 数量
            BigDecimal subPrice = position.getSellOrderPrice().subtract(position.getBuyOrderPrice());
            profitAndLose = subPrice.multiply(new BigDecimal(position.getOrderNum()));
            if(Const.StockPositionDirection.buy_fall.equals(position.getOrderDirection())){
                //  如果是买跌，取反
                profitAndLose = profitAndLose.negate();
            }
            //  单子的总盈亏 = 浮动盈亏 - 所有的手续费
            allProfitAndLose = profitAndLose.subtract(position.getOrderFee())
                    .subtract(position.getOrderSpread()).subtract(position.getOrderStayFee());
        }else{
            //  设置持仓单的现价
            StockListVO stockListVO = SinaStockApi.assembleStockListVO(SinaStockApi
                    .getSinaStock(position.getStockGid()));
            nowPrice = stockListVO.getNowPrice();

            //  设置单子的浮动盈亏 = （现价 - 买入价）* 数量
            BigDecimal subPrice = new BigDecimal(nowPrice).subtract(position.getBuyOrderPrice());
            profitAndLose = subPrice.multiply(new BigDecimal(position.getOrderNum()));
            if(Const.StockPositionDirection.buy_fall.equals(position.getOrderDirection())){
                //  如果是买跌，取反
                profitAndLose = profitAndLose.negate();
            }
            //  单子的总盈亏 = 浮动盈亏 - 所有的手续费
            allProfitAndLose = profitAndLose.subtract(position.getOrderFee())
                    .subtract(position.getOrderSpread()).subtract(position.getOrderStayFee());
        }
        PositionProfitVO positionProfitVO = new PositionProfitVO();
        positionProfitVO.setProfitAndLose(profitAndLose);
        positionProfitVO.setAllProfitAndLose(allProfitAndLose);
        positionProfitVO.setNowPrice(nowPrice);

        return positionProfitVO;
    }






    public static void main(String[] args) {
//        BigDecimal a = new BigDecimal("5000");
//        System.out.println(a);
//        System.out.println(a.negate());





    }


}
